package com.crm.system.service.impl;

import com.crm.entity.SysRegion;
import com.crm.system.mapper.SysRegionMapper;
import com.crm.model.RegionArea;
import com.crm.system.service.SysRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysRegionServiceImpl implements SysRegionService {
    @Autowired
    private SysRegionMapper mapper;

    @Override
    public List<SysRegion> findByLevel(int level) {
        return mapper.findByLevel(level);
    }

    @Override
    public List<SysRegion> findRegionList(String regionId) {
        return null;
    }


    @Override
    public List<RegionArea> fillRegion(int level) {

        List<RegionArea> regionAreas = new ArrayList<>();
        List<SysRegion> regions = mapper.findByLitLevel(level);
        for (SysRegion region : regions) {
            if (region.getRegionLevel() == 1) {
                regionAreas.add(new RegionArea(region.getRegionId(), region.getRegionName()));

            } else if (region.getRegionLevel() == 2) {
                RegionArea province = findByRegionId(regionAreas, region.getParentId());
                if (province != null) {
                    if (province.getChildren() == null) {
                        province.setChildren(new ArrayList<>());
                    }
                    province.getChildren().add(new RegionArea(region.getRegionId(), region.getRegionName()));
                }
            } else if (region.getRegionLevel() == 3) {
                for (RegionArea area : regionAreas) {
                    List<RegionArea> cities = area.getChildren();
                    if (cities == null) {
                        break;
                    }
                    RegionArea city = findByRegionId(cities, region.getParentId());

                    if (city != null) {
                        if (city.getChildren() == null) {
                            city.setChildren(new ArrayList<>());
                        }
                        city.getChildren().add(new RegionArea(region.getRegionId(), region.getRegionName()));
                        break;
                    }


                }
            }
        }
        return regionAreas;
    }

    @Override
    public Map<String, String> fillMap() {
        List<SysRegion> list = mapper.findAll();
        Map<String, String> map = new HashMap<>();
        for (SysRegion region : list) {
            map.put(region.getRegionId(), region.getRegionName());
        }
        return map;
    }

    private RegionArea findByRegionId(List<RegionArea> areas, String regionId) {
        for (RegionArea area : areas) {
            if (area.getRegionId().equals(regionId)) {
                return area;
            }
        }
        return null;
    }
}
